package servlets;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.*;
import java.util.*;
import java.net.*;

/**
 * Servlet implementation class DescargarArchivos
 */
public class DescargarArchivos extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DescargarArchivos() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String urlstr = null;
        String user = (String) request.getSession().getAttribute("usuario");
        try {
            response.reset();
            urlstr = request.getParameter("filename");
            System.out.println(urlstr);
            ServletOutputStream sOutStream = response.getOutputStream();
            streamBinaryData(user, urlstr, sOutStream, response);


        } catch (Exception e) {
            e.printStackTrace();
        }
		
	}
	
	
	  private void streamBinaryData(String username, String file, ServletOutputStream outstr, HttpServletResponse resp) throws IOException{
	        String ErrorStr = null;

	        try {
	        BufferedInputStream bis = null;
	        BufferedOutputStream bos = null;
	        String inFile = "/home/constanza/Documentos/tp/DatosPruebaRecursos-1.1/JARs/" + file;
	        int tam = (int) new File(inFile).length();
	        bis = new BufferedInputStream(new FileInputStream(inFile));

	        try {
	            //Asignamos el tipo de fichero jar
	            resp.setContentType("application/x-java-archive "); //Cualquier mime type
	            //Seteamos el tamaño de la respuesta
	            resp.setContentLength(tam);
	            resp.setHeader("Content-Disposition", "attachment;filename=\"" + file + "\"");

	            bos = new BufferedOutputStream(outstr);

	            // Bucle para leer de un fichero y escribir en el otro.
	            byte[] array = new byte[1000];
	            int leidos = bis.read(array);
	            while (leidos > 0) {
	                bos.write(array, 0, leidos);
	                leidos = bis.read(array);
	            }


	            } catch (Exception e) {
	                e.printStackTrace();
	                ErrorStr = "Error Streaming the Data";
	                outstr.print(ErrorStr);
	            } finally {
	                if (bis != null) {
	                    bis.close();
	                }
	                if (bos != null) {
	                    bos.close();
	                }
	                if (outstr != null) {
	                    outstr.flush();
	                    outstr.close();
	                }
	            }

	            } catch (Exception e) {
	                System.out.println("Fichero no encontrado");
	                resp.sendRedirect("fileNotFound.jsp");

	            }

	        }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
